package org.edu.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.interceptor.RequestAware;
import org.edu.model.User;
import org.edu.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;



import com.opensymphony.xwork2.ActionSupport;

/**
 * json 报文类，返回msg Map列表<br>
 * 于登录用 检测用
 * 
 * @author lenove-x
 * @version 1.1
 * 
 */
@Controller
@ParentPackage("struts-default")
@Namespace("/sgin")

public class LoginAction  extends ActionSupport implements RequestAware{

	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private static final Logger logger = Logger
			.getLogger(LoginAction.class);
	private Map<String, Object> request;

	private User user;


	@Autowired
	private UserService userService;

	@Action(value = "login")
	public void login() {
		HttpServletResponse response = ServletActionContext.getResponse();
		HttpSession session =  ServletActionContext.getRequest().getSession();
		response.setContentType("text/html");
		response.setCharacterEncoding("utf-8");
		PrintWriter out = null;
		try {
			out = response.getWriter();
			
			// 获取用户密码
	
				logger.info(user.getAccount() + "请求登录");
				User u= userService.login(user);
				if(null!=u){
					session.setAttribute("user", u);
					out.print("succes");
					//logger.info(user.getAccount() + "登录成功");
				}else{
					out.print("error");
					logger.info(user.getAccount() + "登录失败，帐号或密码错误");
				}
//				logger.info(user.getAccount() + "管理员请求登录");
//				out.print("admin");
//				logger.info(user.getAccount() + "管理员登录成功");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			out.print("error");
			logger.info("获取登录失败");
		}
	}
	/**
	 * 清除session值
	 * @return SUCCESS 回到主页
	 */
	@Action(value = "exit", results = { @Result(name = "success", location = "/index.jsp",type="redirect") })
	public String exit(){

		HttpSession session =  ServletActionContext.getRequest().getSession();
		session.invalidate();
		
		return SUCCESS;
	}


	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}
	public Map<String, Object> getRequest() {
		return request;
	}
	public void setRequest(Map<String, Object> request) {
		this.request = request;
	}



}
